package com.escope.casemanager.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.escope.casemanager.model.HttpResult;
import com.escope.casemanager.model.SysUserCacheInfo;
import com.escope.casemanager.uti.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * Administrator
 * 2024/3/18
 */
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证权限
        if (this.chekcLogin(request, response, handler)) {
            return true;
        }

        String result = JSONObject.toJSONString(HttpResult.loginError());
        OutputStream outputStream = response.getOutputStream();//获取OutputStream输出流
        response.setHeader("content-type", "application/json;charset=UTF-8;");
        byte[] dataByteArr = result.getBytes("UTF-8");//将字符转换成字节数组，指定以UTF-8编码进行转换
        outputStream.write(dataByteArr);//使用OutputStream流向客户端输出字节数组
        return false;
    }


    /**
     * 是否登录
     *
     * @param handler
     * @return
     */
    private boolean chekcLogin(HttpServletRequest request, HttpServletResponse response, Object handler) {
        SysUserCacheInfo user = redisUtil.getCacheUser(request);
        if (user != null && user.getUser() != null && user.getUser().getId() != null && user.getUser().getId() > 0) {

            return true;
        }
        return false;
    }
}
